package cn.com.zero.web.util;

import cn.com.zero.base.exception.ErrorCodeException;
import cn.com.zero.db.vo.PageParamsVO;
import cn.com.zero.db.vo.PageVO;
import com.github.pagehelper.ISelect;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @author xiongxj
 * @version 1.0.0
 * @Description 分页请求工具类
 * @createTime 2023/2/9 10:03
 */
public class PageRequestUtil {

    /**
     * 获取分页信息
     *
     * @param select 查询接口实现
     * @return 分页信息
     */
    public static <T> PageVO<T> getPageInfo(ISelect select) {
        Page<T> page = PageHelper.startPage(getPageParams()).doSelectPage(select);
        PageVO<T> pageVo = new PageVO<>();
        pageVo.setPages(page.getPages());
        pageVo.setTotal(page.getTotal());
        pageVo.setList(page);

        return pageVo;
    }

    /**
     * 获取分页请求信息
     *
     * @return PageRequestVO 请求分页信息
     */
    public static PageParamsVO getPageParams() {
        HttpServletRequest request = HttpRequestUtil.getRequest();
        String pageNum = request.getParameter("pageNum");
        if (!StringUtils.hasLength(pageNum)) {
            throw new ErrorCodeException(-90001L, new String[]{"分页查询缺少必要的参数:pageNum"});
        }
        String pageSize = request.getParameter("pageSize");
        if (!StringUtils.hasLength(pageSize)) {
            throw new ErrorCodeException(-90001L, new String[]{"分页查询缺少必要的参数:pageSize"});
        }

        //通过request获取参数；当pageSize=0时查询全部数据；支持pageNum、pageSize、orderBy("id desc");注意：参数区分大小写。当pageSize=0时，排序列不生效；
//        Page page = PageHelper.startPage(request);

        PageParamsVO pageParamsVo = new PageParamsVO();
        pageParamsVo.setPageNum(Integer.parseInt(pageNum));
        pageParamsVo.setPageSize(Integer.parseInt(pageSize));
        pageParamsVo.setOrderBy(request.getParameter("orderBy"));

        return pageParamsVo;
    }
}
